﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MacomberMapSystem.Common.Serialization;
using System.Data.Common;

namespace MacomberMapSystem.Common.User_Interfaces
{
    /// <summary>
    /// (C) 2012, Michael E. Legatt, Ph.D.
    /// This form displays an update notification and asks the user for a decision on action
    /// </summary>
    public partial class MM_Update_Notification : Form
    {
        /// <summary>
        /// Initialize our update form
        /// </summary>
        /// <param name="Repository"></param>
        /// <param name="FilesToUpdate"></param>
        public MM_Update_Notification(MM_Repository Repository, Dictionary<String,Version[]> FilesToUpdate)
        {
            InitializeComponent();
            this.Text = "Application update - " + Application.ProductName;
            StringBuilder sB = new StringBuilder();
            sB.AppendLine("<html><head><title>" + this.Text + "</title></head><body><h1>Update " + Application.ProductName + "?</h1>");
            sB.AppendLine("<table border=\"1\"><tbody><tr><th>File</th><th>Version</th><th>Changes</th>");
            foreach (KeyValuePair<string,Version[]> kvp in FilesToUpdate)            
                for (int a=0; a < kvp.Value.Length; a++)
                    using (DbCommand dCmd = Repository.Db.CreateCommand("SELECT Changes FROM MM_VERSIONS WHERE NAME=:0 AND VERSION=:1", kvp.Key, kvp.Value[a].ToString()))
                    {
                        Object inVal = dCmd.ExecuteScalar();
                        sB.AppendLine("<tr>" + (a == 0 ? "<td rowspan=\"" + kvp.Value.Length + "\">" + kvp.Key + "</td>" : "") + "<td>" + kvp.Value[a].ToString() + "</td><td>" + (inVal is String ? (string)inVal : "&nbsp;") + "</td></tr>");
                    }
            sB.AppendLine("</tbody></table></body></html>");
            wBrow.Navigate("about:blank");
            wBrow.Refresh();
            wBrow.Document.Write(sB.ToString());

        }

        /// <summary>
        /// When our form resizes, update everything
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MM_Update_Notification_Resize(object sender, EventArgs e)
        {
            try
            {
                btnNo.Top = btnYes.Top = btnCancel.Top = DisplayRectangle.Bottom - btnCancel.Height - 5;
                btnCancel.Left = DisplayRectangle.Right - btnCancel.Width - 5;
                btnNo.Left = btnCancel.Left - btnNo.Width - 5;
                btnYes.Left = btnNo.Left - btnYes.Width - 5;
                wBrow.Width = btnCancel.Right - wBrow.Left;
                wBrow.Height = btnYes.Top - wBrow.Top;
            }
            catch
            { }

        }
    }
}
